// index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabValue: 1,
    keyWord: "",
    fishTickets: [
    ],
    newsList: [],
    siteList: [],
    day: "",
    citys: [
      {name: "南京市", id: 320100, parent_id: 320000, distance: 13.243614567602197},
      {id: 341100, parent_id: 340000, name: "滁州市", distance: 40.03611419641088},
      {id: 340500, parent_id: 340000, name: "马鞍山市", distance: 42.64789314048559}
    ],
    cityValue: ['320100'],
    cityText: '南京',
    keys:{
      label: "name",
      value: "id"
    },
    cityVisible: false,
    positionArr: [
      {name: "通州", id: 1},
      {name: "房山", id: 2},
      {name: "雨花台区", id: 3}
    ],
    position: {name:"通州",id:1},
    isTimeShow:false,
    isNameShow:false,
    timeShowId: 0,
    nameShowId: 0
  },
  goto: function (e) {
    if (e.currentTarget.dataset.url=='/pages/groupBuying/groupBuying') {
      let item=e.currentTarget.dataset.item
      item.latitude= wx.getStorageSync('currentPosition').lat
      item.longitude= wx.getStorageSync('currentPosition').lon
      item.mobile_phone=wx.getStorageSync('mobile_phone')
      let itemJson=JSON.stringify(item)
      let url=e.currentTarget.dataset.url
      wx.navigateTo({
        url: `${url}?itemJson=${itemJson}`,
      });
    }else{
      wx.navigateTo({
      url: e.currentTarget.dataset.url,
    });
    }
    
  },
  getDay(e) {
    this.setData({
      day: e.detail.day
    });
  },
  getPosition(e) {
    this.setData({
      position: e.detail.position
    });
    var data= {
      latitude: wx.getStorageSync('currentPosition').lat,
      longitude: wx.getStorageSync('currentPosition').lon,
      city: this.data.position.id,
      // keyWord: this.data.keyWord,
      // time: '2024-08-26',
      mobile_phone: wx.getStorageSync('mobile_phone'),
    }
    this.getTicketList(data)
    this.getNewsList(data)
    this.getPlaceList(data)
  },
  getPositionInfo(e) {
    this.setData({
      positionInfo: e.detail.position
    });
  },
  getPositionSite(e) {
    this.setData({
      positionSite: e.detail.position
    });
  },
  getData() {
    let today = new Date();
    let year = today.getFullYear();
    let month = (today.getMonth() + 1) < 10 ? '0' + (today.getMonth() + 1) : (today.getMonth() + 1);
    let day = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
    this.setData({
      day: year + "-" + month + "-" + day,
      day2: year + "-" + month + "-" + day
    })
  },
  onSearch({
    detail
  }) {
    console.log(`modelValue: ${detail.value}`, this.data);
  },
  onTabsChange(event) {
    this.setData({
      tabValue: event.detail.value
    });
    console.log(`Change tab, tab-panel value is ${event.detail.value}.`);
  },

  onTabsClick(event) {
    console.log(`Click tab, tab-panel value is ${event.detail.value}.`);
  },

  onStickyScroll(event) {
    console.log(event.detail);
  },
  onPickerChange(e) {
    console.log('picker change:', e.detail);
    const { value } = e.detail;
    const { label } = e.detail;
    this.setData({
      cityText: label[0],
      cityVisible: false,
      cityValue: value,
    });
    let data = {
      latitude: wx.getStorageSync('currentPosition').lat,
      longitude: wx.getStorageSync('currentPosition').lon,
      city: value[0]
    }
    this.getCityArea(data)
  },
  onColumnChange(e) {
    console.log('picker pick:', e);
  },
  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onCityPicker() {
    console.log(123, this.data)
    this.setData({ cityVisible: true });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1 //这个数字是当前页面在tabBar中list数组的索引
      })
    }
    this.getData()
    this.checkLogin()
  },
  // 获取鱼票列表
  getTicketList(data) {
    app.request('get', '/fishnews/getTicketInfo', data, res =>{
      this.setData({fishTickets: res.data.data.newsInfo})
    })
  },
  // 获取资讯列表
  getNewsList(data) {
    app.request('get', '/fishnews/getNewsInfo', data, res =>{
      let newsList = res.data.data.newsInfo
      this.setData({newsList: newsList})
    })
  },
  // 获取钓场列表
  getPlaceList (data){
    app.request('get', '/fishnews/getPlaceInfo', data, res =>{
      this.setData({siteList: res.data.data.newsInfo})
    })
  },
  // 获取城市和区域
  getCityArea(data){
    app.request('get', '/fishnews/getTicketCity', data, res =>{
      this.setData({
        citys:res.data.data.cityList,
        cityText:res.data.data.use_city.name,
        cityValue:[res.data.data.use_city.id],
        positionArr:res.data.data.areaList,
        position:res.data.data.areaList[0],
      })
      var data= {
        latitude: wx.getStorageSync('currentPosition').lat,
        longitude: wx.getStorageSync('currentPosition').lon,
        city: this.data.position.id,
        // keyWord: this.data.keyWord,
        // time: '2024-08-26',
        mobile_phone: wx.getStorageSync('mobile_phone'),
      }
      this.getTicketList(data)
      this.getNewsList(data)
      this.getPlaceList(data)
    })
  },
  // 收藏钓场
  changeFavorite(e){
    var that = this
    let item = e.currentTarget.dataset.favorite
    console.log(item)
    let list = that.data.siteList
    list[e.currentTarget.dataset.index].is_favorite = item.is_favorite==1?0:1
    this.setData({siteList: list})

    app.request('POST', '/user/editUserFavorites?mobile_phone='+wx.getStorageSync('mobile_phone'), {
      "favorites_state": item.is_favorite==1?0:1,
      "fish_place_id": item.id
    }, res => {
			console.log(res)
    })
  },
  checkLogin() {
    wx.login({
      success: (wxres) => {
        let data = {
          code: wxres.code
        }
        wx.getLocation({
          geocode: true,
          type: 'wgs84',
          success: (res) => {
            console.log(res, '获取当前位置')
            let obj={lat:res.latitude,lon:res.longitude}
            wx.setStorageSync('currentPosition', obj)
          },
          complete:(res)=>{
            var data ={}
            if(res.errMsg == "getLocation:ok"){
              data = {
                latitude: res.latitude,
                longitude: res.longitude
              }
              this.getCityArea(data)
            }else{
              this.getCityArea(data)
            }
          }
        });
        wx.request({
          url: 'https://adminii.sengain.top/fishApi/user/wxlogin',
          method: 'get',
          data: data,
          dataType: 'json',
          success: (res) => {
            let userInfo = res.data.data.userInfo
            wx.setStorageSync('token', userInfo.token)
            wx.setStorageSync('mobile_phone', userInfo.mobile_phone)
          }
        })
      },
    })
  },
  showfishtime(e){
    if((e.currentTarget.dataset.item.id == this.data.timeShowId) && this.data.isTimeShow){
      this.setData({
        isTimeShow: false,
        timeShowId: 0,
      })
      return false
    }
    this.setData({
      isTimeShow: true,
      timeShowId: e.currentTarget.dataset.item.id,
    })
  },
  showfishname(e){
    if((e.currentTarget.dataset.item.id == this.data.nameShowId) && this.data.isNameShow){
      this.setData({
        isNameShow: false,
        nameShowId: 0,
      })
      return false
    }
    this.setData({
      isNameShow: true,
      nameShowId: e.currentTarget.dataset.item.id,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})